1   /*
2    * Copyright (C) 2008 The Guava Authors
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    * http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package com.google.common.collect;
18  
19  import static com.google.common.collect.CollectPreconditions.checkNonnegative;
20  
21  import com.google.common.annotations.GwtCompatible;
22  import com.google.common.base.Supplier;
23  
24  import java.io.Serializable;
25  import java.util.HashMap;
26  import java.util.Map;
27  
28  import javax.annotation.Nullable;
29  
30  /**
31   * Implementation of {@link Table} using hash tables.
32   *
33   * <p>The views returned by {@link #column}, {@link #columnKeySet()}, and {@link
34   * #columnMap()} have iterators that don't support {@code remove()}. Otherwise,
35   * all optional operations are supported. Null row keys, columns keys, and
36   * values are not supported.
37   *
38   * <p>Lookups by row key are often faster than lookups by column key, because
39   * the data is stored in a {@code Map<R, Map<C, V>>}. A method call like {@code
40   * column(columnKey).get(rowKey)} still runs quickly, since the row key is
41   * provided. However, {@code column(columnKey).size()} takes longer, since an
42   * iteration across all row keys occurs.
43   *
44   * <p>Note that this implementation is not synchronized. If multiple threads
45   * access this table concurrently and one of the threads modifies the table, it
46   * must be synchronized externally.
47   * 
48   * <p>See the Guava User Guide article on <a href=
49   * "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Table">
50   * {@code Table}</a>.
51   *
52   * @author Jared Levy
53   * @since 7.0
54   */
55  @GwtCompatible(serializable = true)
56  public class HashBasedTable<R, C, V> extends StandardTable<R, C, V> {
57    private static class Factory<C, V>
58        implements Supplier<Map<C, V>>, Serializable {
59      final int expectedSize;
60      Factory(int expectedSize) {
61        this.expectedSize = expectedSize;
62      }
63      @Override
64      public Map<C, V> get() {
65        return Maps.newHashMapWithExpectedSize(expectedSize);
66      }
67      private static final long serialVersionUID = 0;
68    }
69  
70    /**
71     * Creates an empty {@code HashBasedTable}.
72     */
73    public static <R, C, V> HashBasedTable<R, C, V> create() {
74      return new HashBasedTable<R, C, V>(
75          new HashMap<R, Map<C, V>>(), new Factory<C, V>(0));
76    }
77  
78    /**
79     * Creates an empty {@code HashBasedTable} with the specified map sizes.
80     *
81     * @param expectedRows the expected number of distinct row keys
82     * @param expectedCellsPerRow the expected number of column key / value
83     *     mappings in each row
84     * @throws IllegalArgumentException if {@code expectedRows} or {@code
85     *     expectedCellsPerRow} is negative
86     */
87    public static <R, C, V> HashBasedTable<R, C, V> create(
88        int expectedRows, int expectedCellsPerRow) {
89      checkNonnegative(expectedCellsPerRow, "expectedCellsPerRow");
90      Map<R, Map<C, V>> backingMap =
91          Maps.newHashMapWithExpectedSize(expectedRows);
92      return new HashBasedTable<R, C, V>(
93          backingMap, new Factory<C, V>(expectedCellsPerRow));
94    }
95  
96    /**
97     * Creates a {@code HashBasedTable} with the same mappings as the specified
98     * table.
99     *
100    * @param table the table to copy
101    * @throws NullPointerException if any of the row keys, column keys, or values
102    *     in {@code table} is null
103    */
104   public static <R, C, V> HashBasedTable<R, C, V> create(
105       Table<? extends R, ? extends C, ? extends V> table) {
106     HashBasedTable<R, C, V> result = create();
107     result.putAll(table);
108     return result;
109   }
110 
111   HashBasedTable(Map<R, Map<C, V>> backingMap, Factory<C, V> factory) {
112     super(backingMap, factory);
113   }
114 
115   // Overriding so NullPointerTester test passes.
116 
117   @Override public boolean contains(
118       @Nullable Object rowKey, @Nullable Object columnKey) {
119     return super.contains(rowKey, columnKey);
120   }
121 
122   @Override public boolean containsColumn(@Nullable Object columnKey) {
123     return super.containsColumn(columnKey);
124   }
125 
126   @Override public boolean containsRow(@Nullable Object rowKey) {
127     return super.containsRow(rowKey);
128   }
129 
130   @Override public boolean containsValue(@Nullable Object value) {
131     return super.containsValue(value);
132   }
133 
134   @Override public V get(@Nullable Object rowKey, @Nullable Object columnKey) {
135     return super.get(rowKey, columnKey);
136   }
137 
138   @Override public boolean equals(@Nullable Object obj) {
139     return super.equals(obj);
140   }
141 
142   @Override public V remove(
143       @Nullable Object rowKey, @Nullable Object columnKey) {
144     return super.remove(rowKey, columnKey);
145   }
146 
147   private static final long serialVersionUID = 0;
148 }